package com.thlws.rabbitmq.worker;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

/**
 * 工人模式(多劳多得)
 * 无需设置Exchange信息 
 * 注意此时与 routingKey,Exchange 无任何关联
 * 
 * 本质是Producer,Consumer 使用相同QueueName进行数据传输,客户端设置每次仅获取一笔数据.
 * 同一笔数据只会发到一个消费端，可以理解实现了负载均衡方式的消费.
 *
 */
public class Consumer {
	
	private final static String QUEUE_NAME = "hello";

	public static void main(String[] argv) throws Exception {
		
		
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("116.228.212.36");
        factory.setUsername("hanley");
        factory.setPassword("hanley");
        factory.setVirtualHost("/test");
        
        
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.basicQos(1);//设置每次获取一条消息

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
        	
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        
        //true表示自动确认消息
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
        
        
    }

}
